import { Toast } from '../utils/util'

export const request = (params: any) => {
  const {
    url,
    method = "GET",
    data ={},
    contentType = "application/json",
  } = params

  console.log('url:',url)
  console.log('method:',method)
  console.log('data:',data)
  console.log('contentType:',contentType)

  const token = wx.getStorageSync("token") || "";

  let header = {
    "Content-Type": contentType,
    "Authorization": token
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${url}`,
      data: data,
      method: method,
      header: header,
      success: (res) => {
        let code = res.statusCode
        switch(code) {
          case 401:
            Toast('请重新登录!')
            wx.navigateTo({
              url: '../pages/login/login'
            })
          case 402:
            Toast('账号不可用!')
            break
          case 403:
            Toast('请登录')
            wx.navigateTo({
              url: '../pages/register/register'
            })
            break
          default:
            let data = res.data as Record<string, any>
            let logicCode = data['code']
            switch(logicCode) {
              case "401":
                Toast('请重新登录!')
                wx.navigateTo({
                  url: '../pages/login/login'
                })
              case "404":
              Toast('请重新登录!')
              wx.navigateTo({
                url: '../pages/login/login'
              })
              case "500":
                Toast("网络错误")
                reject(data)
            }
            resolve(res)
        }
      },
      fail: (err) => {
        Toast("网络错误")
        reject(err)
      }
    })
  })
}

export const Get = (params:any) => {
  params["method"] = "GET"
  return new Promise((resolve, reject) => {
    request(params).then(resolve).catch(reject)
  })
}

export const Post = (params:any) => {
  params["method"] = "POST"
  return new Promise((resolve, reject) => {
    request(params).then(resolve).catch(reject)
  })
}
